<?php

use think\facade\Db;

/**
 * 打印函数
 *
 * @param [type] $str
 * @return void
 */
function p($str)
{
    echo '<pre>';
    print_r($str);
    echo '</pre>';
}
/**
 * 读取配置项
 *
 * @param string $key
 * @param integer $group
 * @return void
 */
function getHpConfig($key = '', $group = 0)
{
    $field = 'name,value';
    $model = new \hangpu8\hpcms\model\Webconfig;
    $map = [];
    $data = [];
    if ($group) {
        $map['cid'] = $group;
    }
    if ($key) {
        $map['name'] = $key;
        $info = $model->where($map)->field($field)->find();
        if ($info) {
            $info = $info->toArray();
            return $info['value'];
        } else {
            $data = '';
        }
    } else {
        $list = $model
            ->where($map)
            ->order('id asc')
            ->field($field)
            ->select()
            ->toArray();
        foreach ($list as $value) {
            $data[$value['name']] = $value['value'];
        }
    }
    return $data;
}
/**
 * 获得目录下的所有文件路径并复制到指定的目录下面($old_dir：目标文件目录 $new_dir：需要复制到的文件目录，$quanxian：设置权限
 *
 * @param string $old_dir
 * @param string $new_dir
 * @param integer $quanxian
 * @return void
 */
function copy_to_file(string $old_dir, string $new_dir, $quanxian = 0755)
{
    if (!is_dir($new_dir)) { //判断有没有目录，没有则创建
        @mkdir($new_dir, $quanxian, true);
    }
    $res = '';
    $temp = scandir($old_dir);
    if (is_array($temp) && count($temp) > 2) {
        unset($temp[0], $temp[1]);
        foreach ($temp as $key => $val) {
            $file_url = $old_dir . DIRECTORY_SEPARATOR . $val;
            $xin_dir = $new_dir . DIRECTORY_SEPARATOR . $val; //组件新的目录
            if (is_dir($file_url)) { //是否是目录
                copy_to_file($file_url, $xin_dir);
            } elseif (is_file($file_url)) {
                $res = copy($file_url, $xin_dir);
            }
        }
    }
    return $res;
}
/**
 * 下划线转驼峰
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
function camelize($uncamelized_words,$separator='_')
{
    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}
/**
 * 驼峰命名转下划线命名
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
function uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}
/**
 * 获取附件管理器Key
 *
 * @param string $url
 * @param string $table
 * @return void
 */
function setUploadKey(string $url,string $table)
{
    $key = basename($url);
    $key = substr(basename($key),0,strrpos(basename($key),"."));
    $map['key'] = $key;
    $info = Db::name('uploadify')->where($map)->field('key')->find();
    if (!$info) {
        throw new Exception("找不到附件管理器key");
    }
    if (!$info['key']) {
        throw new Exception("附件管理器key出错");
    }
    // 设置关联
    $data['ctime'] = date('Y-m-d H:i:s');
    $data['table_name'] = $table;
    $data['up_key'] = $info['key'];
    Db::name('uploadify_relation')->save($data);

    // 返回key
    return $info['key'];
}
/**
 * 获取附件管理器的URL
 *
 * @param [type] $key
 * @return void
 */
function getUploadKey($key)
{
    $map['key'] = $key;
    $info = Db::name('uploadify')->where($map)->field('path')->find();
    if (!$info) {
        throw new Exception("找不到附件管理器文件");
    }
    if (!$info['path']) {
        throw new Exception("附件管理器文件路径出错");
    }
    // 返回key
    return $info['path'];
}
/**
 * 删除附件关联
 *
 * @param string $key
 * @param string $table_name
 * @param boolean $isDel
 * @return void
 */
function delUploadRelation(string $key,string $table_name,bool $isDel = false)
{
    $map['up_key'] = $key;
    $map['table_name'] = $table_name;
    if ($isDel) {
        $fileInfo = \hangpu8\hpcms\model\UploadifyRelation::with('profile')->where($map)->find();
        if (!$fileInfo) {
            throw new Exception("找不到附件表关联数据");
        }
        $rootPath = str_replace("\\","/",dirname(dirname(dirname(dirname(__DIR__)))));
        $publicPath = "{$rootPath}/public";
        $filePath = $fileInfo->profile->path;
        // 删除
        if ($fileInfo->together(['profile'])->delete()) {
            // 删除文件
            unlink("{$publicPath}/{$filePath}");

            // 返回状态
            return true;
        }
        return false;
    }else{
        return Db::name('reloadify_relation')->where($map)->delete();
    }
}